﻿using Minio;
using Minio.DataModel;
using Minio.Exceptions;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http;

namespace Thingpower.SS.OSS.WebAPI
{
    [RoutePrefix("oss/api")]
    public class OSSController : ApiController
    {
        //private static MinioClient minio = new MinioClient("www.yd.lwedu.sh.cn:80",
        //        "M17ZRJAVXG47TKPCQ6TG",
        //        "6iWJ2+Jxiq2eV+yKDHp6ibRQ1b1oEPVk0014CQCs"
        //        );

        private static MinioClient minio = new MinioClient("www.yd.lwedu.sh.cn:80",
                "thingpower",
                "xb64315078"
                );

        [HttpGet, Route("hello")]
        public IHttpActionResult GetString()
        {
            return Ok("hello");
        }

        [HttpGet, Route("buckets")]
        public IHttpActionResult GetBucketsList()
        {
            // Create an async task for listing buckets.
            var getListBucketsTask = minio.ListBucketsAsync();

            // Iterate over the list of buckets.
            foreach (Bucket bucket in getListBucketsTask.Result.Buckets)
            {
                //Console.Out.WriteLine(bucket.Name + " " + bucket.CreationDate);
            }

            return Json<List<Bucket>>(getListBucketsTask.Result.Buckets);
        }

        [HttpGet, Route("objects")]
        public IHttpActionResult GetObjectsList()
        {
            try
            {
                // Check whether 'mybucket' exists or not.
                Task<bool> found = minio.BucketExistsAsync("xwsqxy");
                if (found.Result)
                {
                    // List objects from 'my-bucketname'
                    IObservable<Item> observable = minio.ListObjectsAsync("xwsqxy");

                    List<string> _listItem = new List<string>();

                    IDisposable subscription = observable.Subscribe(
                            item => _listItem.Add(item.Key),
                            ex => Console.WriteLine("OnError: {0}", ex.Message),
                            () => Console.WriteLine("OnComplete: {0}"));

                    return Json<List<string>>(_listItem);
                }
                else
                {
                    Console.Out.WriteLine("mybucket does not exist");
                    return NotFound();
                }
            }
            catch (MinioException e)
            {
                Console.Out.WriteLine("Error occurred: " + e);
                return InternalServerError();
            }
        }
    }
}